package com.zhuoli.service.springboot.redis.repository.repository;

import com.zhuoli.service.redis.client.template.redis.RedisTemplate;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

@Component
@AllArgsConstructor
@Slf4j
public class RedisHashRepository {

    private RedisTemplate redisTemplate;

    public Long hset(String key, String field, String value) {
        return redisTemplate.execute(jedis -> jedis.hset(key, field, value));
    }

    public String hget(String key, String field) {
        return redisTemplate.execute(jedis -> jedis.hget(key, field));
    }

    public String hget(String key, String field, Integer db) {
        return redisTemplate.execute(jedis -> {
            jedis.select(db);
            return jedis.hget(key, field);
        });
    }

    public Long hdel(String key, String field) {
        return redisTemplate.execute(jedis -> jedis.hdel(key, field));
    }


    public <K, V> Map<K, V> getHashMap(String key,
                                       Function<String, K> keyBuilder,
                                       Function<String, V> valueBuilder) {
        return redisTemplate.execute(jedis -> {
            Map<K, V> result = new HashMap<>();
            Map<String, String> ret = jedis.hgetAll(key);
            for (Map.Entry<String, String> o : ret.entrySet()) {
                result.put(keyBuilder.apply(o.getKey()), valueBuilder.apply(o.getValue()));
            }
            return result;
        });
    }

    public Map<String, String> getHashInfo(String key) {
        return redisTemplate.execute(jedis -> jedis.hgetAll(key));
    }

    public List<String> getHashValues(String key) {
        return redisTemplate.execute(jedis -> jedis.hvals(key));
    }

}
